
public class Seq implements ISeq {

	private int val = 0;
	private int currentPlayer = -1; //player ID of current Seq, start at -1 as an invalid value
	private int playerID = 0;
	private int opponentID = 0;
	private int[] slots = new int[GameLogic.tokensToWin];
	private int counter = 0; // keeps track of placement of next token in slots array
	private boolean full = false;  // Tells whether the slots array is full
	private int actualTokens = 0;
	
	public Seq(int playerID, int opponentID){
		this.playerID = playerID;
		this.opponentID = opponentID;
	}
	
	
	
	public void flush(){
		counter = actualTokens = 0;
		full = false;
		for (int i = 0; i < slots.length; i++) {
			slots[i] = -1;
		}
	}
	
	private void internalFlush() {
		boolean blocked = false;
		int openSlots = 0;
		actualTokens = 0;
		for (int i = counter-1; i >= 0; i--) {
			if (slots[i] == 0) openSlots++;
			else {
				blocked = true;
				break;
			}
		}
		if (!blocked){
			for (int i = GameLogic.tokensToWin-1; i > counter; i--) {
				if (slots[i] == 0) openSlots++;
				else {
					blocked = true;
					break;
				}
			}
		}
		counter = openSlots;
		if (counter < GameLogic.tokensToWin) full = false;
	}
	
	@Override
	public void push(int token) {
		if (token > 0 && token != currentPlayer){
			internalFlush();
			currentPlayer = token;
		}
		if (full){
			if (slots[counter] == currentPlayer && token == 0) actualTokens--;
			else if (slots[counter] != currentPlayer && token != 0) actualTokens++;
		} else if (token != 0) actualTokens++;
		slots[counter] = token;
		if (counter < GameLogic.tokensToWin-1) counter++;
		else {
			counter = 0;
			full = true;
		}
		if (full) {
			if (currentPlayer == playerID) val = val + actualTokens*actualTokens;
			else if (currentPlayer == opponentID){
				val = val - actualTokens*actualTokens;
				if (actualTokens > 2) val = val;
			}
//			int add = 0;
//			for (int i = 0; i < slots.length; i++) {
//				if (slots[i] == currentPlayer) add++;
//			}
//			if (currentPlayer == playerID) val = val + add*add;
//			else if (currentPlayer == opponentID){
//				val = val - add*add;
//				if (add > 2) val = val*3;
//			}
		}
		
	}

	@Override
	public int value() {
		return val;
	}



	@Override
	public void reset() {
		val = 0;
	}

}
